<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Organization extends Model
{
    use HasFactory,SoftDeletes;



    public static function boot()
    {
        parent::boot();

        static::creating(function ($model) {
            if (!$model->app_id) {
                $model->app_id = static::findAvailableAppId();
                if (!$model->app_id) {
                    return false;
                }
            }

            if (!$model->app_secret) {
                $model->app_secret = static::findAvailableAppSecret();
                if (!$model->app_secret) {
                    return false;
                }
            }
        });
    }

    public static function createOrganization($data)
    {
        if(static::where('name',$data['name'])->first()){
            throw new \App\Exceptions\RuntimeException('组织名已存在');
        }

        $m = new static();

        $m->name = $data['name'];
        $m->save();

        return $m;
    }

    public static function findAvailableAppId()
    {


        $prefix = 'im'.date('YmdHis');
        for ($i = 0; $i < 10; $i++) {
            $appId = $prefix.str_pad(random_int(0, 9999999999), 10, '0', STR_PAD_LEFT);
            if (!static::query()->where('app_id', $appId)->exists()) {
                return $appId;
            }
        }
        \Log::warning('find appId no failed');

        return false;
    }
    public static function findAvailableAppSecret()
    {


        for ($i = 0; $i < 10; $i++) {

            $appSecret = \Str::random(40);

            if (!static::query()->where('app_secret', $appSecret)->exists()) {
                return $appSecret;
            }
        }
        \Log::warning('find appSecret no failed');

        return false;
    }
}
